import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import PropTypes from 'prop-types';
import {getDetail, submitPartOrderPlan, abandonPartOrderPlan} from './api';
import {injectIntl} from './intl';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {DATETIME_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {partOrderPlanStatus, currency} from '../Enum';
import styles from './style.css';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const {Description} = DescriptionList;

class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                        rowVersion: res.data.rowVersion
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleSubmitClick = () => {
        this.setState({loading: true});
        const data = this.state.data;
        submitPartOrderPlan(data.id, {rowVersion: data.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    };
    handleAbandonClick = () => {
        this.setState({loading: true});
        const data = this.state.data;
        abandonPartOrderPlan(data.id, {rowVersion: data.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    render() {
        const {formatMessage} = this.props.intl;
        const data = this.state.data || {};
        const totalVariety = this.state.details.filter(o => o.n1Quantity > 0 || o.n2Quantity > 0 || o.n3Quantity > 0 || o.n4Quantity > 0).length;
        const totalN1Variety = this.state.details.filter(o => o.n1Quantity > 0).length;
        const totalN2Variety = this.state.details.filter(o => o.n2Quantity > 0).length;
        const totalN3Variety = this.state.details.filter(o => o.n3Quantity > 0).length;
        const totalN4Variety = this.state.details.filter(o => o.n4Quantity > 0).length;
        let totalQuantity = 0;
        let totalN1Quantity = 0;
        let totalN2Quantity = 0;
        let totalN3Quantity = 0;
        let totalN4Quantity = 0;
        let totalFee = 0;
        let totalN1Fee = 0;
        let totalN2Fee = 0;
        let totalN3Fee = 0;
        let totalN4Fee = 0;
        this.state.details.forEach(o => {
            totalQuantity += (o.n1Quantity + o.n2Quantity + o.n3Quantity + o.n4Quantity);
            totalN1Quantity += o.n1Quantity;
            totalN2Quantity += o.n2Quantity;
            totalN3Quantity += o.n3Quantity;
            totalN4Quantity += o.n4Quantity;
            totalFee += (o.n1Quantity + o.n2Quantity + o.n3Quantity + o.n4Quantity) * o.price;
            totalN1Fee += o.n1Quantity * o.price;
            totalN2Fee += o.n2Quantity * o.price;
            totalN3Fee += o.n3Quantity * o.price;
            totalN4Fee += o.n4Quantity * o.price;
        });
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            width: 200,
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            width: 350,
            dataIndex: 'partName',
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.description',
                defaultMessage: '英文描述'
            }),
            width: 200,
            dataIndex: 'description',
            render: text => <Ellipsis tooltip fullWidthRecognition length={24}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.n2Quantity',
                defaultMessage: 'N+2月订购数量'
            }),
            width: 180,
            dataIndex: 'n2Quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.n3Quantity',
                defaultMessage: 'N+3月订购数量'
            }),
            width: 180,
            dataIndex: 'n3Quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.n4Quantity',
                defaultMessage: 'N+4月订购数量'
            }),
            width: 200,
            dataIndex: 'n4Quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.productCategoryCode',
                defaultMessage: '适用车型'
            }),
            width: 200,
            dataIndex: 'productCategoryCode',
            render: text => <Ellipsis tooltip fullWidthRecognition length={20}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            width: 100,
            dataIndex: 'minPackSize',
        }, {
            title: formatMessage({
                id: 'newPanel.column.unit',
                defaultMessage: '计量单位'
            }),
            width: 100,
            dataIndex: 'unit',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            width: 100,
            dataIndex: 'price',
            render: text => formatAmount(text)
        }];
        if(this.props.initDate.isDealerUser)
            colums.push({
                title: formatMessage({
                    id: 'newPanel.column.partReplacementCode',
                    defaultMessage: '替换件编号'
                }),
                width: 250,
                dataIndex: 'partReplacementCode'
            });
        else
            colums.splice(3, 0,
                {
                    title: formatMessage({
                        id: 'newPanel.column.n1Quantity',
                        defaultMessage: 'N+1月订购数量'
                    }),
                    width: 180,
                    dataIndex: 'n1Quantity',
                });
        colums.push({
            title: formatMessage({
                id: 'newPanel.column.stockQuantity',
                defaultMessage: '上月总代库存'
            }),
            width: 250,
            dataIndex: 'stockQuantity'
        }, {
            title: formatMessage({
                id: 'newPanel.column.partReplacementCode',
                defaultMessage: '替换件编号'
            }),
            width: 250,
            dataIndex: 'partReplacementCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.replacementQuantity',
                defaultMessage: '替换件总代库存'
            }),
            width: 280,
            dataIndex: 'replacementQuantity',
        });
        const actions = [];
        if(hasPermissions(this.props.permissions, PERMISSIONS.update) &&
        hasPermissions(data.options, PERMISSIONS.update) && this.props.initDate.isDealerUser)
            actions.push((
                <Button key="return" href={`#${routes.update.format(this.props.id)}`} className={styles.btnMargin} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detailPanel.operation.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            ));
        if(hasPermissions(this.props.permissions, PERMISSIONS.submit) &&
            hasPermissions(data.options, PERMISSIONS.submit) && this.props.initDate.isDealerUser)
            actions.push((
                <WrappedPopconfirm
                    id={data.id}
                    key="submit"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleSubmitClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detailPanel.operation.save',
                            defaultMessage: '保存'
                        })}
                    </Button>
                </WrappedPopconfirm>
            ));
        if(hasPermissions(this.props.permissions, PERMISSIONS.approve) &&
            hasPermissions(data.options, PERMISSIONS.approve) && !this.props.initDate.isDealerUser)
            actions.push((
                <Button key="return" href={`#${routes.approve.format(this.props.id)}`} className={styles.btnMargin} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detailPanel.operation.approve',
                        defaultMessage: '审核'
                    })}
                </Button>
            ));
        if(hasPermissions(this.props.permissions, PERMISSIONS.abandon) &&
            hasPermissions(data.options, PERMISSIONS.abandon) && this.props.initDate.isDealerUser)
            actions.push((
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否确认作废？'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detailPanel.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detailPanel.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small" className={styles.btnMargin}>
                        {this.props.intl.formatMessage({
                            id: 'detailPanel.operation.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            ));
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row>
                            <Col span={6}>
                                { formatMessage({
                                    id: 'detailPanel.baseInfo',
                                    defaultMessage: '备件需求计划单'
                                })}
                            </Col>
                            <Col className={styles.textAlign} span={18}>
                                {actions}
                            </Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detail.operation.code',
                                defaultMessage: '编号'
                            })}>{data.code}
                            </Description>
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.branchCode',
                                    defaultMessage: '营销分公司编号'
                                })}>{data.branchCode}
                                </Description>}
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.branchName',
                                    defaultMessage: '营销分公司名称'
                                })}>{data.branchName}
                                </Description>}
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.brandCode',
                                    defaultMessage: '品牌编号'
                                })}>{data.brandCode}
                                </Description>
                            }
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.brandName',
                                    defaultMessage: '品牌名称'
                                })}>{data.brandName}
                                </Description>}
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.dealerCode',
                                    defaultMessage: '总代编号'
                                })}>{data.dealerCode}
                                </Description>}
                            {!this.props.initDate.isDealerUser &&
                                <Description term={formatMessage({
                                    id: 'detail.operation.dealerName',
                                    defaultMessage: '总代名称'
                                })}>{data.dealerName}
                                </Description>
                            }
                            <Description term={formatMessage({
                                id: 'detail.operation.orderPlanYear',
                                defaultMessage: '计划年份'
                            })}>{data.orderPlanYear}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.orderPlanMonth',
                                defaultMessage: '计划月份'
                            })}>{data.orderPlanMonth}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.totalFee',
                                defaultMessage: '总金额'
                            })}>{formatAmount(totalFee)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.totalQuantity',
                                defaultMessage: '总数量'
                            })}>{totalQuantity || ''}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.totalVariety',
                                defaultMessage: '总品种数'
                            })}>{totalVariety || ''}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.status',
                                defaultMessage: '状态'
                            })}>{ conventEnumValueToString(partOrderPlanStatus, data.status)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.createTime',
                                defaultMessage: '提报日期'
                            })}>{ formatDateTime(data.createTime, DATETIME_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.createName',
                                defaultMessage: '创建人姓名'
                            })}>{data.createName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.modifyName',
                                defaultMessage: '编辑人姓名'
                            })}>{data.modifyName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.modifyTime',
                                defaultMessage: '编辑时间'
                            })}>{formatDateTime(data.modifyTime, DATETIME_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.submitterName',
                                defaultMessage: '提交人姓名'
                            })}>{data.submitterName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.submitTime',
                                defaultMessage: '提交时间'
                            })}>{formatDateTime(data.submitTime, DATETIME_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.confirmorName',
                                defaultMessage: '审核人姓名'
                            })}>{data.confirmorName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.confirmTime',
                                defaultMessage: '审核时间'
                            })}>{formatDateTime(data.confirmTime, DATETIME_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.abandonerName',
                                defaultMessage: '作废人姓名'
                            })}>{data.abandonerName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.abandonTime',
                                defaultMessage: '作废时间'
                            })}>{formatDateTime(data.abandonTime, DATETIME_FORMAT)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.approvedContent',
                                defaultMessage: '审核意见'
                            })}>{data.approvedContent}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detail.operation.details',
                            defaultMessage: '备件需求计划清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={colums}
                                dataSource={this.state.details}
                                pagination={false}
                                scroll={{
                                    x: 'max-content',
                                    y: 600
                                }}
                                size="small"
                                bordered={true}
                                footer={() => <div>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN2Quantity',
                                                defaultMessage: 'N+2月订购数量汇总'
                                            })}>{totalN2Quantity}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN3Quantity',
                                                defaultMessage: 'N+3月订购数量汇总'
                                            })}>{totalN3Quantity}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN4Quantity',
                                                defaultMessage: 'N+4月订购数量汇总'
                                            })}>{totalN4Quantity}
                                            </Description>
                                            {!this.props.initDate.isDealerUser &&
                                                <Description className={styles.descriptionWidth} term={formatMessage({
                                                    id: 'newPanel.operation.totalN1Quantity',
                                                    defaultMessage: 'N+1月订购数量汇总'
                                                })}>{totalN1Quantity}
                                                </Description>
                                            }
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN2Fee',
                                                defaultMessage: 'N+2月订购金额汇总'
                                            })}>{formatAmount(totalN2Fee)}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN3Fee',
                                                defaultMessage: 'N+3月订购金额汇总'
                                            })}>{formatAmount(totalN3Fee)}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN4Fee',
                                                defaultMessage: 'N+4月订购金额汇总'
                                            })}>{formatAmount(totalN4Fee)}
                                            </Description>
                                            {!this.props.initDate.isDealerUser &&
                                                <Description className={styles.descriptionWidth} term={formatMessage({
                                                    id: 'newPanel.operation.totalN1Fee',
                                                    defaultMessage: 'N+1月订购金额汇总'
                                                })}>{formatAmount(totalN1Fee)}
                                                </Description>
                                            }
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN2Variety',
                                                defaultMessage: 'N+2月订购品种汇总'
                                            })}>{totalN2Variety}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN3Variety',
                                                defaultMessage: 'N+3月订购品种汇总'
                                            })}>{totalN3Variety}
                                            </Description>
                                            <Description className={styles.descriptionWidth} term={formatMessage({
                                                id: 'newPanel.operation.totalN4Variety',
                                                defaultMessage: 'N+4月订购品种汇总'
                                            })}>{totalN4Variety}
                                            </Description>
                                            {!this.props.initDate.isDealerUser &&
                                                <Description className={styles.descriptionWidth} term={formatMessage({
                                                    id: 'newPanel.operation.totalN1Variety',
                                                    defaultMessage: 'N+1月订购品种汇总'
                                                })}>{totalN1Variety}
                                                </Description>
                                            }
                                        </DescriptionList>
                                    </Row>
                                </div>} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{formatMessage({
                        id: 'detail.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div >
        );
    }
}

DetailPanel.propTypes = {
    initDate: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};


import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getInitDate = selectorFactory(['page', 'domainData', 'initData']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
    initDate: getInitDate(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
